<template>
    <div class="echarts-root">
        <div :id="ecahrtId" style="width: 100%;" :style="{ height: cHeight }"></div>
    </div>
</template>

<script setup>
//普通柱状图
import * as echarts from 'echarts';
import { onMounted } from 'vue';

const ecahrtId = 'echartsBarDom' + Math.floor(Math.random() * 10000);

const props = defineProps({
    // 图表高度，带单位
    cHeight: {
        type: String,
        default: '220px',
    },
    list: {
        type: Array,
        default: () => {
            return []
        }
    }
});

watch(() => props.list, value => initEcharts(value))

//图表对象
const echartsObj = ref(null);

//初始化图表
const initEcharts = (seriesDatas = []) => {
    let echartsDom = document.getElementById(ecahrtId);
    echarts.dispose(echartsDom);
    echartsObj.value = echarts.init(echartsDom);

    let xDatas = []
    let resultList = []
    if (!seriesDatas || seriesDatas.length == 0) {
        for (let i = 0; i < 6; i++) {
            resultList.push(0)
            xDatas.push('')
        }
    } else {
        seriesDatas.map(item => {
            xDatas.push(item.name)
            resultList.push(item.value)
        })
    }

    let option = {
        tooltip: {
            show: true
        },
        // tooltip: {
        //     trigger: 'axis',
        //     axisPointer: {
        //         type: 'shadow'
        //     }
        // },
        xAxis: {
            type: 'category',
            data: xDatas
        },
        yAxis: {
            type: 'value',
            minInterval: 1,
        },
        grid: {
            top: 20,
            left: 40,
            right: 40,
            bottom: 20
        },
        min: 10,
        color: ['#63B8FF'],
        series: [{
            type: 'bar',
            barWidth: 35,
            data: resultList,
            showBackground: true,
            backgroundStyle: {
                color: 'rgba(180, 180, 180, 0.1)'
            },
            label: {
                normal: {
                    show: true,//开启显示
                    position: 'top',//柱形上方
                    textStyle: { //数值样式
                        color: '#666'
                    }
                }
            }
        }]
    };
    echartsObj.value.setOption(option);

    window.addEventListener('resize', () => {
        if (echartsObj.value) {
            echartsObj.value.resize()
        }
    })
}

onMounted(() => {
    initEcharts()
})

</script>

<style lang="scss" scoped>
.echarts-root {
    position: relative;
    width: 100%;
    height: 100%;

    .total-div {
        position: absolute;
        top: 36%;
        left: 50%;
        z-index: 11;
        width: 120px;
        height: 70px;
        margin-left: -60px;
        text-align: center;
        border-radius: 10px;

        .total {
            font-size: 30px;
            color: #000;
        }

        .tag {
            font-size: 14px;
            color: #666;
            margin-top: 5px;
        }
    }
}
</style>